package cn.jn.lhm.netty.part02;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/4/25 - 23:13
 **/
@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {
        // 新建一个专门处理非IO事件的 EventLoopGroup,可以处理一些耗时比较长的任务，防止IO线程处理耗时长的任务然后阻塞其他Channel的IO操作
        DefaultEventLoopGroup taskHandler = new DefaultEventLoopGroup(2);
        new ServerBootstrap()
                // boss(1个线程)    worker(2个线程)
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        // 加入处理器
                        ch.pipeline().addLast("handle1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info("server 收到{}消息:{}", ch, buf.toString(StandardCharsets.UTF_8));
                                ctx.fireChannelRead(msg);
                            }
                        }).addLast(taskHandler, "handle2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info("server 收到{}消息:{}", ch, buf.toString(StandardCharsets.UTF_8));
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
